from django.db import transaction
from rest_framework import permissions
from rest_framework.decorators import action
from rest_framework.views import APIView
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.system.models import SystemLog, Upload, Option
from apps.system.serializers import OptionDictSerializer
from apps.product.models import Product
from .serializers import AdornPediaSerializer
from .models import AdornPedia, AdornPediaImgs
from .filters import AdornPediaFilter


class AdornPediaDictViewSet(APIView):
    permission_classes = [permissions.IsAdminUser]

    # 返回产品的字典参数
    def get(self, request):
        ret = {
            'category': OptionDictSerializer(Option.objects.filter(type=Option.ADORN_PEDIA_CATEGORY, enable=True),
                                             many=True).data
        }
        return response_ok(ret)


class AdornPediaViewSet(CustomModelViewSet):
    '''后台article CRUD操作'''
    permission_classes = [permissions.IsAdminUser]
    queryset = AdornPedia.objects.filter()
    serializer_class = AdornPediaSerializer

    def update(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                print(request.data)
                del_upload = None
                instance = self.get_object()
                if instance.thumbnail.id != request.data['thumbnail']:
                    del_upload = instance.thumbnail
                super(CustomModelViewSet, self).update(request, *args, **kwargs)
                if del_upload:
                    del_upload.delImage()
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    def filter_queryset(self, queryset):
        f = AdornPediaFilter(self.request.GET, queryset=self.queryset)
        return f.qs

    @action(methods=['post'], detail=True)
    def relate_products(self, request, pk):
        '''关联产品'''
        try:
            new_relate_ids = request.data
            adorn_pedia = AdornPedia.get_instance_by_id(pk)
            with transaction.atomic():
                adorn_pedia.relate_products.clear()
                adorn_pedia.relate_products.add(*Product.objects.filter(id__in=new_relate_ids))
            return response_ok()
        except Exception as e:
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def upload_image(self, request, pk):
        adorn_pedia = AdornPedia.get_instance_by_id(pk)
        file = request.FILES.get('file')
        if not file:
            return response_error(u'未找到上传的数据')
        try:
            with transaction.atomic():
                upload = Upload.objects.upload(file, 'adorn_pedia/' + str(adorn_pedia.id))
                AdornPediaImgs.objects.create(adorn_pedia=adorn_pedia, image=upload)
                return response_ok()
        except Exception as e:
            return response_error(str(e))
